package cn.highedu.boot01.controller;

import cn.highedu.boot01.entity.User;
import cn.highedu.boot01.util.DBUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@Controller
public class UserController {
    /**
     * 用户注册
     */
    @RequestMapping("/register")
    @ResponseBody
    public String register(User user) {
        String message = "";
        Connection con = null;
        PreparedStatement ps = null;
        String sql = "insert into user(username, password, nickname) values(?, ?, ?)";
        try {
            con = DBUtil.getConnection();
            ps = con.prepareStatement(sql);
            ps.setString(1, user.getUsername());
            ps.setString(2, user.getPassword());
            ps.setString(3, user.getNickname());
            int result = ps.executeUpdate();
            if (result > 0) {
                message = "注册成功 用户名是:" + user.getUsername();
            }
            else {
                message = "注册失败";
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(con, ps);
        }
        return message;
    }
    /**
     * 用户登录
     */
    @RequestMapping("/login")
    @ResponseBody
    public String login(User user) {
        String message = "";
        Connection con = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        // 根据用户名查询 如果能查出结果, 说明用户名存在, 否则用户名不存在
        String sql = "select * from user where username=?";
        try {
            con = DBUtil.getConnection();
            ps = con.prepareStatement(sql);
            ps.setString(1, user.getUsername());
            rs = ps.executeQuery();
            // 判断是否查询出了结果
            if (rs.next()) {
                // 取出查询到的密码
                String password = rs.getString("password");
                // 和用户输入的密码比较
                if (password.equals(user.getPassword())) {
                    message = "登录成功 欢迎" + user.getUsername() + "登录";
                }
                else {
                    message = "登录失败 密码错误";
                }
            }
            else {
                message = "登录失败 用户名不存在";
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(con, ps, rs);
        }
        return message;
    }
}
